var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
// const chalk = require('chalk');
const logger = require('morgan');

// 路由加载
const mount = require('mount-routes');
// 解决跨域
const cors = require('cors')
// 访问 .env环境配置文件
const dotenv = require('dotenv');
dotenv.config();

var app = express();
// 改写 使用app.js 启动
var http = require('http');
var server = http.createServer(app);

// 加载数据库模型
const db = require("./models/index");
db.sequelize.sync();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 加载日志输出
app.use(logger('dev'));

// 加载统一响应的返回 
const UnifiedResponse = require('./utils/resextra-util');
app.use(UnifiedResponse);

const varifyPassport = require('./utils/token-util');
// 设置 passport 验证路径 ('/api/private/' 开头的都需要进行token)
app.use('/api/private/*', varifyPassport.varifyToken);
app.use('/api/private/*', varifyPassport.permissionAuth);
app.use(varifyPassport.errorToken);

// 处理请求参数解析
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 解析cookie
app.use(cookieParser());

//设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

// 解决跨域
app.use(cors());
// 设置跨域和响应数据格式
app.all('/api/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*') // 让其它网站可以跨域访问
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, token')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.header('Content-Type', 'application/json;charset=UTF-8') // 设置响应内容的类型
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  if (req.method == 'OPTIONS') res.send(200)
  /*让options请求快速返回*/
  else next()
});

// 带路径的用法并且可以打印出路由表  true 代表展示路由表在打印台
mount(app, path.join(process.cwd(), '/routes'), true)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// app.listen(process.env.DEV_PORT, () => {
//   console.log(chalk.bold.green(`项目启动成功: ${process.env.DEV_URL}:${process.env.DEV_PORT}`));
// });
server.listen(process.env.DEV_PORT, () => {
  console.log(`项目启动成功: ${process.env.DEV_URL}:${process.env.DEV_PORT}`)
});
